<template>
<div style="width:100%;height:100%;">
  <a-button type="primary" @click="setJSON">新增围栏</a-button>||
  <a-button type="primary" @click="stop">停止绘图</a-button>||
  <a-button type="primary" @click="start">开始绘图</a-button>||
  <a-button type="primary" @click="stop">保存绘图</a-button>
  <a-button type="primary" @click="test">测试</a-button>
  <div id="maps" class="map">
    <div id="popup" class="ol-popup">
      <a href="#" id="popup-closer" class="ol-popup-closer"></a>
      <div id="popup-content" class="popup-content"></div>
    </div>
  </div>
</div>
</template>

<script>
import Point from "ol/geom/Point";
import {
  GeoJSON
} from "ol/format";
import Draw from "ol/interaction/Draw";
import {
  getCenter
} from "ol/extent";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import {
  Map,
  View,
  Feature
} from "ol";
import "ol/ol.css";
import MultiPoint from "ol/geom/MultiPoint";

import {
  Circle as CircleStyle,
  Fill,
  Stroke,
  Icon,
  Style
} from "ol/style";
// 投影
import Overlay from "ol/Overlay";
const JSONURl = require("./JSON/5.json");
export default {
  data() {
    return {
      map: null,
      x: null,
      y: null,
      x1: null,
      y1: null,
      Icon: [{
          x: 2827.970491535012,
          y: 6871.263035307627,
          type: "1.png",
        },
        {
          x: 985.5882702715971,
          y: 3669.2510749397316,
          type: "2.png",
        },
        {
          x: 1618.7480305399586,
          y: 10292.284252992747,
          type: "p.png",
        },
      ],
      personIcon: [{
          x: 27.970491535012,
          y: 6871.263035307627,
          type: "p1.png",
        },
        {
          x: 485.5882702715971,
          y: 1269.2510749397316,
          type: "p1.png",
        },
        {
          x: 18.7480305399586,
          y: 10292.284252992747,
          type: "p1.png",
        },
      ],
      value: "Polygon",

      // JSONd图层
      vector: null,
      // 图标层
      vectorLayer: null,
      personLayer: null,
      source: null,
      draw: null,
      // 围栏图层数据
      weilan: [{
        type: "Feature",
        properties: {
          name: "围栏一",
        },
        geometry: {
          type: "Polygon",
          coordinates: [
            [
              [-3827.970491535012, 36871.263035307627],
              [10384.970491535012, 36871.263035307627],
              [10384.970491535012, 71.263035307627],
              [-3827.970491535012, 71.263035307627],
              [-3827.970491535012, 36871.263035307627],
            ],
          ],
        },
      }, ],
      // 围栏层
      weilanLayer: null,
    };
  },
  watch: {
    source: {
      deep: true,
      immediate: true,
      handler(a) {
        // console.log(a.getGeometry());
      },
    },
  },
  mounted() {
    this.init();
    //添加JSON底图
    this.addJSON();
    //  添加弹框图层
    this.addPopup();
    // 添加小人图层
    this.personIocn();
    // 图标层
    this.addIocn(this.Icon);
    // 增加绘制图层
    // this.setJSON();
    this.addInteraction();
  },
  methods: {
    // 初始化地图
    init() {
      this.source = new VectorSource({});
      let vector = new VectorLayer({
        source: this.source,
      });
      let extent = [200, 200, 4000, 200];
      this.map = new Map({
        view: new View({
          center: [0, 0],
          zoom: 10,
          // 最大放大倍数
          maxZoom: 14,
          // 最小缩放倍数
          minZoom: 10,
        }),
        // 图层 layers 配置图层的数据源
        layers: [vector],
        target: "maps",
      });
    },
    /**
     * 点击弹出框
     */
    addPopup() {
      // 使用变量存储弹窗所需的 DOM 对象
      var container = document.getElementById("popup");
      var closer = document.getElementById("popup-closer");
      var content = document.getElementById("popup-content");
      // 创建一个弹窗 Overlay 对象
      this.overlay = new Overlay({
        element: container, //绑定 Overlay 对象和 DOM 对象的
        autoPan: false, // 定义弹出窗口在边缘点击时候可能不完整 设置自动平移效果
        autoPanAnimation: {
          duration: 250, //自动平移效果的动画时间 9毫秒）
        },
      });

      // 将弹窗添加到 map 地图中
      this.map.addOverlay(this.overlay);
      let _that = this;
      /**
       * 为弹窗添加一个响应关闭的函数
       */
      closer.onclick = function () {
        _that.overlay.setPosition(undefined);
        closer.blur();
        return false;
      };
      /**
       * 添加单击map 响应函数来处理弹窗动作
       */
      this.map.on("click", function (e) {
        // let coordinate = transform(e.coordinate, "EPSG:3857", "EPSG:4326");
        let feature = _that.map.forEachFeatureAtPixel(e.pixel, function (
          feature
        ) {
          return feature;
        });

        if (feature == undefined) {
          _that.overlay.setPosition(undefined);
          closer.blur();
        } else {
          content.innerHTML = feature.get("name");
          _that.overlay.setPosition(e.coordinate); //把 overlay 显示到指定的 x,y坐标
        }
      });
    },
    // 点击增加图标
    addIocn(con) {
      let arr = [];
      for (let i = 0; i < con.length; i++) {
        let iconFeature = new Feature({
          geometry: new Point([con[i].x, con[i].y]),
          name: `我的标识${i}`,
        });
        let src = require(`./JSON/${con[i].type}`);
        let iconStyle = new Style({
          image: new Icon({
            anchor: [0.5, 0.5],
            src: src,
          }),
        });
        iconFeature.setStyle(iconStyle);
        arr.push(iconFeature);
      }

      this.vectorLayer = new VectorLayer({
        source: new VectorSource({
          features: arr,
        }),
        zIndex: 21,
      });
      this.map.addLayer(this.vectorLayer);
    },
    // 渲染JSON底层
    addJSON() {
      // =====
      let source = new VectorSource({
        features: new GeoJSON().readFeatures(JSONURl),
      });

      let styles = new Style({
        stroke: new Stroke({
          width: 3,
          color: "pink",
        }),
        fill: new Fill({
          color: "#ccc",
        }),
      });
      // 绘画图层
      this.vector = new VectorLayer({
        source: source,
        minZoom: 1,
        // projection: "EPSG:4326", //projection 设置地图的投影坐标系统  默认是EPSG:3857
        renderBuffer: 200,
        zIndex: 1,
        style: styles,
      });
      this.map.addLayer(this.vector);
    },
    // 渲染小人图层
    personIocn() {
      let arr = [];
      for (let i = 0; i < this.personIcon.length; i++) {
        let iconFeature = new Feature({
          geometry: new Point([this.personIcon[i].x, this.personIcon[i].y]),
          name: `person${i}`,
        });
        let src = require(`./JSON/${this.personIcon[i].type}`);
        let iconStyle = new Style({
          image: new Icon({
            anchor: [0.5, 0.5],
            src: src,
          }),
        });
        iconFeature.setStyle(iconStyle);
        arr.push(iconFeature);
      }

      this.personLayer = new VectorLayer({
        source: new VectorSource({
          features: arr,
        }),
        zIndex: 22,
      });
      this.map.addLayer(this.personLayer);
    },

    // 停止绘画
    stop() {
      this.map.removeInteraction(this.draw);
      this.value = false;
      this.draw = null;
      this.addInteraction();
    },
    start() {
      this.value = "Polygon";
      this.addInteraction();
    },
    // 增加绘制图形
    addInteraction() {
      let styles = new Style({
        stroke: new Stroke({
          width: 3,
          color: "rgba(0,255,255,1)",
        }),
        fill: new Fill({
          color: "rgba(0,255,255,0.1)",
        }),
      });
      if (this.value) {
        this.draw = new Draw({
          source: this.source,
          type: this.value,
          style: styles,
        });
        // 将互动层添加到地图
        this.map.addInteraction(this.draw);
        this.draw.on("drawend", function (e) {
          // 获取互动坐标
          const geometry = e.feature.getGeometry();
          console.log(geometry.getCoordinates());
          // console.log(geometry.extent_);
        });
      }
    },
    // 自定义图形
    setJSON() {
      let styles = [
        new Style({
          stroke: new Stroke({
            color: "blue",
            width: 3,
          }),
          fill: new Fill({
            color: "rgba(0, 0, 255, 0.1)",
          }),
        }),
        new Style({
          image: new CircleStyle({
            radius: 3,
            fill: new Fill({
              color: "orange",
            }),
          }),
          geometry: function (feature) {
            const coordinates = feature.getGeometry().getCoordinates()[0];
            return new MultiPoint(coordinates);
          },
        }),
      ];
      let geojsonObject = {
        type: "FeatureCollection",
        crs: {
          type: "name",
          properties: {
            name: "EPSG:3857",
          },
        },
        features: this.weilan,
      };
      let a = new GeoJSON().readFeatures(geojsonObject);

      let source = new VectorSource({
        features: a,
      });

      this.weilanLayer = new VectorLayer({
        source: source,
        style: styles,
        zIndex: 30,
      });
      this.map.addLayer(this.weilanLayer);
    },
    //增加绘画图层addFeature
    test() {
      this.map.removeLayer(this.weilanLayer);
      this.setJSON();
      // this.weilanLayer.source = [];
    },
    // 增加图形Interactio
  },
};
</script>

<style lang="scss" scoped>
.map {
  width: 100%;
  height: 90%;
}

.ol-popup {
  position: absolute;
  background-color: #ccc;
  -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  // padding: 15px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 12px;
  left: -50px;
}

.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}

.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}

.ol-popup-closer {
  text-decoration: none;
  position: absolute;
  top: 2px;
  right: 8px;
}

.popup-content {
  width: 400px;
}

.ol-popup-closer:after {
  content: "✖";
}

#marker {
  width: 20px;
  height: 20px;
  background: red;
  border-radius: 50%;
}

#textInfo {
  width: 200px;
  height: 40px;
  line-height: 40px;
  background: burlywood;
  color: yellow;
  text-align: center;
  font-size: 20px;
}
</style>
